package com.mvcMovie.handler;

import com.mvcMovie.bean.User;
import com.mvcMovie.service.LoginAndExitService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
@RequestMapping("/login")
public class LoginHandler {

    @Autowired
    private LoginAndExitService loginAndExitService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @RequestMapping("/")
    public String cookie(){
        loginAndExitService.CookieJudge(request,response);
        User user = (User)request.getSession().getAttribute("user");
        if (user!=null){
            return "redirect:/user/list";
        }
        return "redirect:/index";
    }

    @RequestMapping("/up")
    public String login(
            @RequestParam(value="username",required = false) String username,
            @RequestParam(value="password",required = false) String password,
            @RequestParam(value="f",required = false, defaultValue = "0") String f,
            @RequestParam(value="d",required = false, defaultValue = "0") String d) {
        User user;
        //证明没有找到Cookie信息
        //进行正常登录
        user = loginAndExitService.Login(username, password, d);
        //存储到session域中，保持登录状态
        request.getSession().setAttribute("user",user);
        //判断用户是否选择了免登录，如果选择了，则给浏览器返回对应的cookie(管理员无法免登录)
        if ("1".equals(f) && !"1".equals(d)){
            loginAndExitService.NoLoginJudgment(request,response);
        }
        //判断用户是否登录成功，如果不成功重新登录
        if (user == null) {
            return "redirect:/index";
        }
        //成功返回对应页面
        return redirectToRolePage(d);
    }

    @RequestMapping("/exit")
    public String exit(){
        loginAndExitService.Exit(request,response);
        return "redirect:/index";
    }

    private String redirectToRolePage(String d) {
        return "1".equals(d) ? "redirect:/root/list" : "redirect:/user/list";
    }
}
